var pool = require('../modules/db_mysql').pool;
var uid = require('../modules/uuid');//用于生成id
function Category(category) {
    this.title = category.title;
    this.status = category.status;
    this.order = category.order;
    this.created_time = category.created_time;
    this.last_modified_time = category.last_modified_time;
}

module.exports = Category;


//新增用户
Category.prototype.save = function save(callback) {

    // 用户对象
    var tag = {
        title: this.title,
        status: this.status,
        order: this.order,
        created_time: this.created_time,
        last_modified_time: this.last_modified_time
    };
    uuid = uid.v4();
    //插入数据库
    var sql ="insert into tag (id, title, status, order, created_time, last_modified_time) values(?,?, 1, 50, now(), now())";

    pool.getConnection(function(err, connection) {
        connection.query(sql, [uuid, tag.title],function(err, result, fields){
            connection.release();
            if (err) {
                callback(err);
            } else {
                //返回用户id
                return callback(err, result, fields);
            }
        });
    });
};


Category.search = function search(condition, callback) {
    condition.findOne = condition.findOne || false;
    condition.searchType = condition.searchType || 0;  //0 only view
    var sql = "";

    if(condition.searchType == 0){
        sql = "select c.id, c.title "
            + "from category c ";
    }
    else{
        sql = "select c.id, c.title, count(e.id) as count "
            + "from category c "
            + "left join essay e on c.id=e.category_id and e.status=1 "
            + "group by c.id ";
        //+ "where c.name='"+username+"'";
    }
    console.log("category.search:", sql);

    pool.getConnection(function(err, connection) {
        connection.query(sql, function(err, result, fields){
            connection.release();
            if(err){
                callback(err);
            }else{
                console.log("result:", result.length);
                //console.log("fields:", fields);
                callback(err, result);
            }
        });
    });

};